#coding:utf-8
from __future__ import unicode_literals

from django.shortcuts import render,HttpResponse,render_to_response
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required

from deploy.saltapi import SaltAPI
from oms import settings
from oms import  settings_local



# Create your views here.
@login_required
def salt_key_list(request):
    """
    list all key
    """

    user = request.user
    sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'],password=settings.SALT_API['password'])
    minions, minions_pre = sapi.list_all_key()

    return render_to_response('salt/salt_key_list.html', {'all_minions': minions, 'all_minions_pre': minions_pre})

def salt_accept_key(request):
    """
    accept salt minions key
    """

    node_name = request.GET.get('node_name')
    sapi = SaltAPI(url=settings.SALT_API['url'],username=settings.SALT_API['user'],password=settings.SALT_API['password'])
    ret = sapi.accept_key(node_name)
    return HttpResponseRedirect(reverse('deploy:key_list'))

def salt_delete_key(request):
    """
    delete salt minions key
    """

    node_name = request.GET.get('node_name')
    sapi = SaltAPI(url=settings.SALT_API['url'],username=settings.SALT_API['user'],password=settings.SALT_API['password'])
    ret = sapi.delete_key(node_name)
    return HttpResponseRedirect(reverse('deploy:key_list'))

########################################################### 以上是salt key方面的操作###################################################
def remote_execution(request):
    """
    remote command execution
    """
    ret = "禁止使用  shutdown  init  reboot  等危险指令...."
    danger = ('rm', 'reboot', 'init ', 'shutdown','passwd')
    if request.method=='POST':
        tgt = request.POST.get('tgt')
        arg = request.POST.get('arg')
        argcheck = arg not in danger
        if argcheck:
            sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'],password=settings.SALT_API['password'])
            ret = sapi.remote_execution(tgt, 'cmd.run', arg)
        else:
            ret='亲，命令很危险, 你这样子管理员可不开森了.....'

    return render_to_response('salt/salt_remote_execution.html', {'ret': ret})